<template>
  <view class="contacts-page">
    <view class="search-bar">
      <input 
        v-model="searchKeyword"
        placeholder="搜索联系人"
        @input="onSearch"
      />
    </view>
    
    <scroll-view class="contact-list" scroll-y>
      <view 
        v-for="contact in filteredContacts" 
        :key="contact.id"
        class="contact-item"
        @click="viewContact(contact)"
      >
        <image :src="contact.avatar || '/static/default-avatar.png'" class="avatar"></image>
        <view class="contact-info">
          <text class="name">{{ contact.displayName }}</text>
          <text class="department">{{ contact.department }}</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import request from '../../utils/request'

interface Contact {
  id: string
  username: string
  displayName: string
  avatar?: string
  department?: string
}

const searchKeyword = ref('')
const contacts = ref<Contact[]>([])

const filteredContacts = computed(() => {
  if (!searchKeyword.value) return contacts.value
  
  return contacts.value.filter(c => 
    c.displayName.includes(searchKeyword.value) ||
    c.username.includes(searchKeyword.value)
  )
})

onMounted(() => {
  loadContacts()
})

const loadContacts = async () => {
  try {
    const data = await request<Contact[]>({
      url: '/api/users/contacts'
    })
    contacts.value = data
  } catch (error) {
    console.error('加载联系人失败', error)
  }
}

const onSearch = () => {
  // 搜索逻辑已在 computed 中处理
}

const viewContact = (contact: Contact) => {
  uni.navigateTo({
    url: `/pages/contacts/detail?id=${contact.id}`
  })
}
</script>

<style scoped>
.contacts-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.search-bar {
  padding: 20rpx 30rpx;
  background: white;
}

.search-bar input {
  width: 100%;
  height: 70rpx;
  padding: 0 30rpx;
  background: #f5f5f5;
  border-radius: 35rpx;
  font-size: 28rpx;
}

.contact-list {
  flex: 1;
  background: white;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
}

.avatar {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.contact-info {
  flex: 1;
}

.name {
  display: block;
  font-size: 32rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.department {
  font-size: 26rpx;
  color: #999;
}
</style>
